package cn.stylefeng.guns.modular.tao.api;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class GetToken {


    public String DoGetToken(String authCode) throws Exception {
        //	String code = GetAuthCode(param);

        //???p????
        JSONObject obj = new JSONObject();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//?????????????????
        Date now = new Date();
        String time = dateFormat.format(now);
        obj.put("TimeStamp", time);
        obj.put("GrantType", "auth_token");
        obj.put("AuthParam", authCode);
        String jsonParam = obj.toString();
        AESCoder coder = new AESCoder();
        String p = coder.encrypt(jsonParam, Config.app_secret);

        //???sign
        JSONObject signObj = new JSONObject();
        signObj.put("appkey", Config.appkey);
        signObj.put("p", p);
        signObj.put("signkey", Config.sign_key);
        Map<String, Object> newMap = AESCoder.order(AESCoder.parseJSON2Map(signObj.toString()));

        String sign = coder.SHA256(JSONUtils.toJSONString(newMap));

        //??????
        Map<String, String> map = new HashMap<String, String>();
        map.put("appkey", Config.appkey);
        map.put("p", URLEncoder.encode(p, "utf-8"));
        map.put("sign", sign);
        String postString = "";
        for (String in : map.keySet()) {
            postString += in + "=" + map.get(in) + "&";
        }
        postString = postString.substring(0, postString.length() - 1);
        String ret = HttpRequest.sendPost(Config.get_token_url, postString);

        //??????????
        JSONObject jsonObject = JSONObject.parseObject(ret);
        String resp = jsonObject.getJSONObject("response").get("response").toString();
        String gettoken = coder.decrypt(resp, Config.app_secret);
        JSONObject tokenJson = JSONObject.parseObject(gettoken);
        String token = tokenJson.getString("auth_token");
        return token;
    }

    public String GetAuthCode(String param) throws Exception {
        String AuthCode = "";
        String[] params = param.trim().split("&");
        for (int i = 0; i < params.length; i++) {
            if (params[i].toLowerCase().indexOf("auth_code") >= 0 && params[i].toLowerCase().indexOf("=") >= 0) {
                AuthCode = params[i].substring(params[i].toLowerCase().indexOf("="));
                break;
            }
        }
        if (AuthCode != "" && AuthCode.length() > 1) {
            AuthCode = AuthCode.substring(1);
        } else {
            throw new Exception("???????code???");
        }
        return AuthCode;
    }

}


